<?php

class lypoImportstatementsTask extends sfPropelBaseTask
{
	protected function configure()
	{
		$this->namespace        = 'lypo';
		$this->name             = 'import-statements';
		$this->briefDescription = '';
		$this->detailedDescription = <<<EOF
The [lypo:import-statements|INFO] task importeert alle stellingen vanuit "data/cs/stellingen.csv"
Call it with:

  [php symfony lypo:import-statements|INFO]
EOF;
		$this->addArgument('application', sfCommandArgument::REQUIRED, 'The application name');
		// add other arguments here
		$this->addOption('env', null, sfCommandOption::PARAMETER_REQUIRED, 'The environment', 'dev');
		$this->addOption('connection', null, sfCommandOption::PARAMETER_REQUIRED, 'The connection name', 'propel');
		// add other options here
	}

	protected function execute($arguments = array(), $options = array())
	{
		// Database initialization
		$databaseManager = new sfDatabaseManager($this->configuration);
		$connection = Propel::getConnection($options['connection'] ? $options['connection'] : '');
		// add code here

		$file = sfConfig::get('sf_data_dir').DIRECTORY_SEPARATOR.'csv'.DIRECTORY_SEPARATOR.'stellingen.csv';
		if(!file_exists($file)){
			$this->logSection('error',sprintf('%s niet gevonden!',$file),200,'ERR');
			exit;
		}

		$fp = fopen($file,"r");
		if(!$fp){
			$this->logSection('error',sprintf('Unable to open %s',$file),200,'ERR');
			exit;
		}

		//Eerst alles wissen
		LypoStatementPeer::doDeleteAll();
		StatementDayPeer::doDeleteAll();

		//NU de AUTO INCREMENT op 1 zetten (is wel zo mooi)
		$sql =  sprintf('ALTER TABLE %s AUTO_INCREMENT=1;',BaseLypoStatementPeer::TABLE_NAME);
		/* $stmt PreparedStatament */
		$stmt = $connection->prepareStatement($sql);
		$rs = $stmt->executeQuery();
		$i=0;
		$sortorder=0;
		while (($data = fgetcsv($fp, 1000, ";")) !== FALSE) {
			if($i==0){
				$fields=$data;
			}else{
				if($data[0]!=""){
					$s = new LypoStatement();
					$s->setText($data[0]);
					$s->setYoutubeCode($data[1]);
					if($data[2]!=""){
						$dm = split("_",$data[2]);
						$s->setDailymotionCode($dm[0]);
					}
					if($data[3]!=""){
						$s->setVimeoCode($data[3]);
					}
					if($i <= 26 ){
						$s->setForRegistration(true);
					}
					$s->setSortorder($sortorder);
					$s->save();
					$sortorder++;

					echo sprintf("Statement %s: '%s'\n",$i,$s->getText());
				}
			}
				
			$i++;

		}

		for($i=1; $i<=5;$i++){
			$sd = new StatementDay();
			$sd->setDatum(strtotime('today -'.$i.' days'));
			$sd->setStatementId($i);
			$sd->save();
			//Day Statements invoegen
		}

		fclose($fp);
	}
}